package fudan.se.lab2.service;

import fudan.se.lab2.controller.request.RegisterRequest;
import fudan.se.lab2.domain.User;
import fudan.se.lab2.exception.EmailHasBeenRegisteredException;
import fudan.se.lab2.exception.UsernameHasBeenRegisteredException;
import fudan.se.lab2.repository.UserRepository;
import fudan.se.lab2.security.jwt.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author LBW
 */
@Service
public class AuthService {
    private final UserRepository userRepository;
    private final JwtTokenUtil jwtTokenUtil;


    @Autowired
    public AuthService(UserRepository userRepository, JwtTokenUtil jwtTokenUtil) {
        this.userRepository = userRepository;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    public User register(RegisterRequest request) {
        User user;

        user = userRepository.findByUsername(request.getUsername());
        if (user != null) {
            throw new UsernameHasBeenRegisteredException(request.getUsername());
        }
        user = userRepository.findByEmail(request.getEmail());
        if (user != null) {
            throw new EmailHasBeenRegisteredException(request.getEmail());
        }

        User newUser = new User(request.getUsername(), request.getPassword(), request.getFullname(), request.getEmail(), request.getAffiliation(), request.getRegion(), null);
        userRepository.save(newUser);
        return newUser;
    }

    public String login(String username, String password) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User: '" + username + "' not found.");
        } else {
            String correctPassword = user.getPassword();
            if (password.equals(correctPassword)) {
                return jwtTokenUtil.generateToken(user);
            } else {
                return "密码错误！";
            }
        }
    }
}
